﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SocketServer.ServerBase;
using SocketServer;
using IUploading;
using LogLib;

namespace PhotoUploader
{

    public partial class ucTcpServer : UserControl
    {
        /// <summary>
        /// 存储session和对应ip端口号的泛型集合
        /// </summary>
        public Dictionary<string, ClientRequestPackSession> SessionList = new Dictionary<string, ClientRequestPackSession>();

        public TransferServer Server = null;

        private string ipAddress_Connect;

        public Dictionary<string, IUpload> Uploaders
        {
            set 
            {
                Server.Uploaders = value;
            }
            get 
            {
                return Server.Uploaders;
            }
        }

        enum OperateType
        {
            Add = 1,  //添加
            Remove = 2  //移除
        }

        public event TakeLogInfo LogUpdated;
        protected void TakeLog(string strInfo)
        {
            string uploadInfo = "[" + DateTime.Now.ToString("HH:mm:ss.ffff") + "] " + strInfo;
            if (LogUpdated != null)
            {
                LogUpdated(strInfo);
            }
        }

        public event UpdateTransferResult TransferResultUpdated;
        protected void UpdateInterfaceActionResult(string name, TransferResult result)
        {
            if (TransferResultUpdated != null)
            {
                TransferResultUpdated(name, result);
            }
        }

        public ucTcpServer()
        {
            Server = new TransferServer();
            InitializeComponent();
        }

        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="str"></param>
        private void SetMessage(string str)
        {
            Log.WriteAsync(str);
            richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(str + "\r\n"); }));
        }

        private void btn_StartListen_Click(object sender, EventArgs e)
        {
            StartServer();
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            StopServer();
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            //从客户端列获取想要发送数据的客户端的ip和端口号,然后从sessionList中获取对应session然后调用send()发送数据
            TransferResponsePackge pack = new TransferResponsePackge();
            pack.Result = TransferResult.PostOK;
            pack.InterfaceName = "FTPUpload";
            pack.Action = TransferAction.Post;
            pack.Code = 9;
            pack.Success = true;
            pack.Add("Path", @"D:\Newest");
            pack.Add("Value", "20190923");
            Server.SendPackage(pack);
        }

        /// <summary>
        /// combobox操作
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="operateType">add 添加项/remove 移除项</param>
        private void ComboboxHandle(string ipAddress, OperateType operateType)
        {
            if (operateType == OperateType.Add)
            {
                cmb_socketlist.Invoke(new Action(() => { cmb_socketlist.Items.Add(ipAddress); }));
            }
            if (operateType == OperateType.Remove)
            {
                cmb_socketlist.Invoke(new Action(() => { cmb_socketlist.Items.Remove(ipAddress); }));
            }
        }

        /// <summary>
        /// 接收连接
        /// </summary>
        /// <param name="session"></param>
        private void appServer_NewSessionConnected(ClientRequestPackSession session)
        {
            //获取远程客户端的ip端口号
            string ipAddress = session.RemoteEndPoint.ToString();
            SessionList.Add(ipAddress, session);
            ipAddress_Connect = session.RemoteEndPoint.ToString();
            ComboboxHandle(ipAddress_Connect, OperateType.Add);
            SetMessage(ipAddress_Connect + "已连接!");
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void appServer_SessionClosed(ClientRequestPackSession session, SuperSocket.SocketBase.CloseReason value)
        {
            string ipAddress = session.RemoteEndPoint.ToString();
            SessionList.Remove(ipAddress);
            ComboboxHandle(ipAddress, OperateType.Remove);
            SetMessage(ipAddress + "已关闭连接!");
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        private void appServer_NewRequestReceived(
            ClientRequestPackSession session,
            TransferDataPackge info)
        {
            SetMessage("接口" + info.InterfaceName + "动作: " + info.Action + " " + info.InParams);
        }

        private void OnTransferDataResponsed(object sender, TransferResponsedEventArgs e)
        {
            TransferResponsePackge pack = e.Packge;
            UpdateInterfaceActionResult(pack.InterfaceName, pack.Result);
            string logInfo = string.Format("接口{0}执行动作{1}结果: {2} \t{3}", pack.InterfaceName, pack.Action, pack.Result, pack.Message);
            TakeLog(logInfo);
        }

        public bool InitServer()
        {
            if (Server.Init())
            {
                SetMessage("服务器初始化成功.");
                Server.NewSessionRequestReceived += appServer_NewRequestReceived;
                Server.NewSessionConnected += appServer_NewSessionConnected;
                Server.SessionClosed += appServer_SessionClosed;
                Server.TransferResponsed += OnTransferDataResponsed;
                return true;
            }
            else
            {
                SetMessage(Server.ErrorMessage);
                return false;
            }     
        }

        public bool StartServer()
        {
            if (Server.Running)
            {
                return true;
            }
            if (Server.StartServer())
            {
                SetMessage("服务器启动成功.");
                return true;
            }
            else
            {
                SetMessage(Server.ErrorMessage);
                return false;
            }
        }

        public void StopServer()
        {
            if (Server.Running)
            {
                Server.Stop();
                SetMessage("服务已关闭.");
            }
        }

        public void CloseServer()
        {           
            Server.NewSessionRequestReceived -= appServer_NewRequestReceived;
            Server.NewSessionConnected -= appServer_NewSessionConnected;
            Server.SessionClosed -= appServer_SessionClosed;
            Server.TransferResponsed -= OnTransferDataResponsed;
            Server.Close();
            SetMessage("服务已停止.");
        }

        private void ucTcpServer_Load(object sender, EventArgs e)
        {         
            
        }

        public bool InitInterfaces(out string msg)
        {
            Server.InitInterfaces("");
            if (Server.CheckInitResult(out msg))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
